import { asyncRoutes, constantRoutes } from '@/router';

import user from './user';

function hasPermission(roles, route) {
    if (route.meta && route.meta.roles) {
        return roles.some(role => route.meta.roles.includes(role));
    } else {
        return true;
    }
}

export function filterAsyncRoutes(routes, roles) {
    const res = [];

    routes.forEach(route => {
        const tmp = { ...route };
        if (hasPermission(roles, tmp)) {
            if (tmp.children) {
                tmp.children = filterAsyncRoutes(tmp.children, roles);
            }
            res.push(tmp);
        }
    });

    return res;
}

const state = {
    routes: [],
    addRoutes: []
};

const mutations = {
    SET_ROUTES: (state, routes) => {
        console.log(routes);
        state.addRoutes = routes;
        state.routes = constantRoutes.concat(routes);
    }
};

const actions = {
    generateRoutes({ commit }, roles) {
        let newMenu = [];
        for (let item1 of asyncRoutes) {
            let flag = false;
            let item = {};
            flag = true;
            item = item1;
            let children = [];
            for (let item2 of item1.children) {
                children.push(item2);
            }
            item.children = children;
            item.redirect = children[0].path;
            if (flag) {
                newMenu.push(item);
            }
        }
        return new Promise(resolve => {
            commit('SET_ROUTES', newMenu);
            resolve(newMenu);
        });
    }
};

export default {
    namespaced: true,
    state,
    mutations,
    actions
};
